package JavaSe;

import com.sun.xml.internal.fastinfoset.tools.FI_DOM_Or_XML_DOM_SAX_SAXEvent;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName interview
 * @Description: TODO
 * @date ${DAT}15:35
 */
public class ClassUtil {
    public static void printClassInfo(Object o){
        Class c = o.getClass();
        System.out.println("类的名称"+ c.getName());
        // 一个成员方法就是一个method对象
        // getMethod()所有的public方法，包括父类继承的public
        // getDeclareMethod()获取该类的所有方法，包括private，但不包括继承的方法

        Method[] methods = c.getMethods();
        // 获取所有的方法包括私有方法
        for (Method method : methods) {
            Class returnType = method.getReturnType();
            System.out.println(returnType.getName());
            // 得到方法名
            System.out.println(method.getName());

            Class[] parameterTypes = method.getParameterTypes();
            for (Class parameterType : parameterTypes) {
                System.out.print(parameterType.getName() + " ");
            }
            System.out.println();
        }
        System.out.println("===================");
        // 获取成员变量的信息
        Field[] fields = c.getFields();
        for (Field field : fields) {
            Class filedType = field.getType();
            System.out.println(filedType.getName() + "   " + field.getName());
        }

        System.out.println("===================");

        // 获取构造函数的信息
        Constructor[] con = c.getDeclaredConstructors();
        for (Constructor constructor : con) {
            System.out.print(constructor.getName() + "(");

            Class[] typeParas = constructor.getParameterTypes();
            for (Class typePara : typeParas) {
                System.out.print(typePara.getName()+" ");
            }
            System.out.println(")");
        }
    }
}
class TestReflect{
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String s = "s";
//        ClassUtil.printClassInfo(s);
        A a = new A();
        Class c = a.getClass();
        Method method = c.getMethod("add",int.class,int.class);
        method.invoke(a,10,10);
    }
}
class A{
    public void add(int a, int b){
        System.out.println(a + b);
    }

    public void toUpper(String a){
        System.out.println(a.toUpperCase());
    }
}


